package com.health.viewscontrols.medical.device.bg;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.utils.HexUtil;
import com.health.model.SanNuoBean;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.health.viewscontrols.medical.base.BaseDeviceActivity1;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.sinocare.multicriteriasdk.DeviceCmdS;
import com.sinocare.multicriteriasdk.MulticriteriaSDKManager;
import com.sinocare.multicriteriasdk.SnCallBack;
import com.sinocare.multicriteriasdk.auth.AuthUtils;
import com.sinocare.multicriteriasdk.bean.BaseDetectionData;
import com.sinocare.multicriteriasdk.entity.BoothDeviceConnectState;
import com.sinocare.multicriteriasdk.entity.DeviceDetectionState;
import com.sinocare.multicriteriasdk.entity.SNDevice;
import com.sinocare.multicriteriasdk.utils.LogUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * 三诺血糖仪  https://gitee.com/sinocare-iot/Sinocare_Detection_SDK_Android/tree/sinocare_ble_2.0.x/
 */
public class BGSannuo2000Activity extends BaseDeviceActivity1 {

    private List<SNDevice> snDevices = new ArrayList<>();

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bg_sannuo);
        // 三诺SDK鉴权结果
        boolean authValid = AuthUtils.isAuthValid();
        if (!authValid) {
            ToastUtils.showShort("SDK认证失败!");
            tv_state.setText("SDK认证失败!");
        }
        Log.d(TAG, "鉴权结果： " + authValid + "  Token值： " + AuthUtils.getAccessToken());

        SNDevice snDevice = new SNDevice();
        snDevice.setMac(deviceEnum.getMac());
        snDevice.setMachineCode("2000");
        snDevice.setProductCode("100015");
        snDevice.setName("三诺臻准2000血糖仪");
        snDevice.setBleNamePrefix("SN-4Y");
        snDevice.setOpenProcessData(false);
        snDevice.setDataProtocolCode(SNDevice.DEVICE_SINO_STANDARD_BLE_01);
        Log.e(TAG, "doBusiness: " + snDevice.toString() );
        snDevices.add(snDevice);
    }

    @Override
    public void startDevice() {
        Log.e(TAG, "startDevice: " + NovaApplication.isSanNuoGLUBleDevice);
        if (!isConnected) {
            showProgressDialog("正在连接" +  deviceEnum.getTitle());
        } else {
            ToastUtils.showShort("设备已连接!");
        }

        // 第一种 默认就是开启扫描设备
        MulticriteriaSDKManager.startConnect(snDevices, !NovaApplication.isSanNuoGLUBleDevice, new SnCallBack(){
            @Override
            public void onDataComing(SNDevice device, BaseDetectionData data){
                //设备数据回调，解析见后面数据结构，实时测量数据与历史测量数据均在此处回调；
                Log.e(TAG, "onDataComing: " + data.toString() );
                saveData(data);
            }

            @Override
            public void onDetectionStateChange(SNDevice device, DeviceDetectionState state){
                Log.e(TAG, "onDeviceStateChange: -----snDevice----" + device.toString());
                //设备数据状态：时间同步成功、历史数据获取成功、清除成功等等
            }

            @Override
            public void onDeviceStateChange(SNDevice device, BoothDeviceConnectState state){
                Log.e(TAG, "onDeviceStateChange: " + state.toString() );
                //连接连接状态 目前只回调连接成功与断开连接
                if (state != null) {
                    showBleState(state);
                }
            }
        });

        /**
         * 第二种 内部关闭扫描过程，直连设备 isScanningBluetooth 是否扫描蓝牙 (注意 开启扫描连接比直连稳定，但是速度快)
         */
        // MulticriteriaSDKManager.startConnect(snDevices,boolean isScanningBluetooth，new SnCallBack(){}

    }

    private void saveData(BaseDetectionData data) {
        try {
            if ("04".equals(data.getCode())) {
                if (data != null && data.getData() != null) {
                    SanNuoBean sanNuoBean = GsonUtils.fromJson(data.getData(), SanNuoBean.class);
                    SanNuoBean.ResultBean result = sanNuoBean.getResult();
                    if (result != null && result.getGLU() != null && result.getGLU().getValue() != null) {
                        String value = result.getGLU().getValue();
                        String unit = result.getGLU().getUnit();
                        if (TextUtils.isEmpty(unit)) {
                            unit = "mmol/L";
                        }
                        tv_state.setText("获取测量结果成功");
                        tv_result.setText("血糖值： " + value  + unit);

                        DeviceShowSaveData.getDataShow(value + "","Sinocare");
                        DeviceShowSaveData.saveXuetang(value + "");
                    }

                }

            } else if ("02".equals(data.getCode())) {
                tv_state.setText("获取测量结果失败");
                tv_result.setText("" + data.getCode()  + "，" + data.getMsg() );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void disconnectDevice() {
        try {
            // 断开连接
            MulticriteriaSDKManager.disConectDevice(snDevices);
            snDevices.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("WrongConstant")
    private void showBleState(BoothDeviceConnectState state) {
        try {
            if (!TextUtils.isEmpty(state.getDesc())) {
                blueToothState.setText(state.getDesc());
            }

            if (state.getmState() == 2) {
                isConnected = true;
                NovaApplication.isSanNuoGLUBleDevice = true;
                cancelProgressDialog();
            } else {
                isConnected = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
